<template>
  <div class="recently-visited">
    <div class="rv-header">
      <h3 class="rv-title">最近访问</h3>
      <div v-if="historyItems.length > 0" class="rv-actions">
        <button class="clear-btn" @click="clearHistory">
          <i class="fas fa-trash-alt"></i>
          清空
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="rv-loading">
      <div class="rv-spinner"></div>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="historyItems.length === 0" class="rv-empty">
      <i class="fas fa-history rv-empty-icon"></i>
      <p class="rv-empty-text">暂无访问记录</p>
    </div>
    
    <div v-else class="rv-list">
      <div 
        v-for="(item, index) in historyItems" 
        :key="index"
        class="rv-item"
        @click="navigateTo(item)"
      >
        <div class="rv-item-icon" :style="{ backgroundColor: getModuleColor(item.module) }">
          <i :class="getModuleIcon(item.module)"></i>
        </div>
        <div class="rv-item-content">
          <div class="rv-item-title">{{ item.title }}</div>
          <div class="rv-item-meta">
            <span class="rv-item-module">{{ getModuleName(item.module) }}</span>
            <span class="rv-item-time">{{ formatTime(item.timestamp) }}</span>
          </div>
        </div>
        <div class="rv-item-actions">
          <button class="rv-action-btn pin" @click.stop="togglePin(item)" :class="{ 'pinned': item.pinned }">
            <i :class="item.pinned ? 'fas fa-thumbtack' : 'far fa-thumbtack'"></i>
          </button>
          <button class="rv-action-btn remove" @click.stop="removeItem(item)">
            <i class="fas fa-times"></i>
          </button>
        </div>
      </div>
    </div>
    
    <div v-if="pinnedItems.length > 0" class="rv-pinned-section">
      <h4 class="rv-pinned-title">已固定项目</h4>
      <div class="rv-pinned-list">
        <div 
          v-for="(item, index) in pinnedItems" 
          :key="index"
          class="rv-pinned-item"
          @click="navigateTo(item)"
        >
          <div class="rv-pinned-icon" :style="{ backgroundColor: getModuleColor(item.module) }">
            <i :class="getModuleIcon(item.module)"></i>
          </div>
          <div class="rv-pinned-content">
            <div class="rv-pinned-title">{{ item.title }}</div>
            <div class="rv-pinned-module">{{ getModuleName(item.module) }}</div>
          </div>
          <button class="rv-pinned-unpin" @click.stop="togglePin(item)">
            <i class="fas fa-thumbtack"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RecentlyVisited',
  data() {
    return {
      loading: false,
      history: [],
      moduleConfig: {
        finance: {
          name: '财务管理',
          color: 'var(--primary-blue)',
          icon: 'fas fa-yen-sign'
        },
        asset: {
          name: '资产管理',
          color: 'var(--purple)',
          icon: 'fas fa-laptop'
        },
        material: {
          name: '物资管理',
          color: 'var(--medical-green)',
          icon: 'fas fa-box-open'
        },
        admin: {
          name: '系统管理',
          color: 'var(--grey)',
          icon: 'fas fa-cogs'
        }
      }
    }
  },
  computed: {
    // 获取最近访问项（已排序、非固定）
    historyItems() {
      return this.history
        .filter(item => !item.pinned)
        .sort((a, b) => b.timestamp - a.timestamp)
    },
    
    // 获取已固定项
    pinnedItems() {
      return this.history.filter(item => item.pinned)
    }
  },
  mounted() {
    this.loadHistory()
  },
  methods: {
    // 加载历史记录
    loadHistory() {
      this.loading = true
      
      // 从本地存储获取历史记录
      try {
        const savedHistory = localStorage.getItem('hplus_visited_history')
        if (savedHistory) {
          this.history = JSON.parse(savedHistory)
        }
      } catch (error) {
        console.error('Failed to load history:', error)
        this.history = []
      }
      
      // 如果没有历史记录，加载一些示例数据（仅供演示）
      if (this.history.length === 0) {
        this.history = this.getMockHistory()
      }
      
      this.loading = false
    },
    
    // 清空历史记录
    clearHistory() {
      // 保留固定项
      this.history = this.history.filter(item => item.pinned)
      this.saveHistory()
    },
    
    // 添加访问记录
    addHistoryItem(item) {
      // 检查是否已存在
      const existingIndex = this.history.findIndex(h => 
        h.path === item.path && h.module === item.module
      )
      
      if (existingIndex >= 0) {
        // 更新时间戳
        this.history[existingIndex].timestamp = Date.now()
      } else {
        // 添加新记录
        this.history.push({
          ...item,
          timestamp: Date.now(),
          pinned: false
        })
        
        // 限制数量（不含固定项）
        const nonPinned = this.history.filter(h => !h.pinned)
        if (nonPinned.length > 20) {
          // 找出最早的非固定项并移除
          const oldest = nonPinned.sort((a, b) => a.timestamp - b.timestamp)[0]
          this.history = this.history.filter(h => h !== oldest)
        }
      }
      
      this.saveHistory()
    },
    
    // 移除单个记录
    removeItem(item) {
      this.history = this.history.filter(h => 
        !(h.path === item.path && h.module === item.module)
      )
      this.saveHistory()
    },
    
    // 切换固定状态
    togglePin(item) {
      const index = this.history.findIndex(h => 
        h.path === item.path && h.module === item.module
      )
      
      if (index >= 0) {
        this.history[index].pinned = !this.history[index].pinned
        this.saveHistory()
      }
    },
    
    // 导航到历史项
    navigateTo(item) {
      // 更新时间戳
      const index = this.history.findIndex(h => 
        h.path === item.path && h.module === item.module
      )
      
      if (index >= 0) {
        this.history[index].timestamp = Date.now()
        this.saveHistory()
      }
      
      // 导航到指定路径
      this.$router.push(item.path)
    },
    
    // 保存历史记录到本地存储
    saveHistory() {
      try {
        localStorage.setItem('hplus_visited_history', JSON.stringify(this.history))
      } catch (error) {
        console.error('Failed to save history:', error)
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const now = new Date()
      const date = new Date(timestamp)
      
      // 今天
      if (date.toDateString() === now.toDateString()) {
        return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 昨天
      const yesterday = new Date()
      yesterday.setDate(now.getDate() - 1)
      if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 7天内
      const daysDiff = Math.floor((now - date) / (1000 * 60 * 60 * 24))
      if (daysDiff < 7) {
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        return `${weekdays[date.getDay()]} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 更早
      return `${date.getMonth() + 1}月${date.getDate()}日`
    },
    
    // 获取模块名称
    getModuleName(moduleKey) {
      return this.moduleConfig[moduleKey]?.name || moduleKey
    },
    
    // 获取模块颜色
    getModuleColor(moduleKey) {
      return this.moduleConfig[moduleKey]?.color || 'var(--grey)'
    },
    
    // 获取模块图标
    getModuleIcon(moduleKey) {
      return this.moduleConfig[moduleKey]?.icon || 'fas fa-file'
    },
    
    // 生成模拟历史数据（仅供演示）
    getMockHistory() {
      const now = Date.now()
      const hour = 3600 * 1000
      const day = 24 * hour
      
      return [
        {
          title: '报销申请',
          module: 'finance',
          path: '/finance/expense',
          timestamp: now - 2 * hour,
          pinned: false
        },
        {
          title: '资产列表',
          module: 'asset',
          path: '/asset/list',
          timestamp: now - 5 * hour,
          pinned: true
        },
        {
          title: '工资条明细',
          module: 'finance',
          path: '/finance/salary/detail',
          timestamp: now - 1 * day,
          pinned: false
        },
        {
          title: '库存管理',
          module: 'material',
          path: '/material/inventory',
          timestamp: now - 2 * day,
          pinned: false
        },
        {
          title: '资产维修申请',
          module: 'asset',
          path: '/asset/repair',
          timestamp: now - 4 * day,
          pinned: false
        },
        {
          title: '用户管理',
          module: 'admin',
          path: '/admin/users',
          timestamp: now - 6 * day,
          pinned: true
        }
      ]
    }
  }
}
</script>

<style scoped>
.recently-visited {
  background-color: var(--background-white);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  overflow: hidden;
}

.rv-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--divider);
}

.rv-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.rv-actions {
  display: flex;
  gap: 8px;
}

.clear-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: var(--radius-md);
  border: none;
  background-color: var(--grey-100);
  color: var(--text-secondary);
  cursor: pointer;
  font-size: 13px;
  transition: all var(--transition-fast);
}

.clear-btn:hover {
  background-color: var(--grey-200);
  color: var(--text-primary);
}

.clear-btn i {
  font-size: 12px;
}

/* 加载状态 */
.rv-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--text-secondary);
}

.rv-spinner {
  width: 28px;
  height: 28px;
  border: 2px solid var(--grey-200);
  border-top-color: var(--primary-blue);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 空状态 */
.rv-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--text-secondary);
}

.rv-empty-icon {
  font-size: 36px;
  margin-bottom: 16px;
  color: var(--grey-300);
}

.rv-empty-text {
  margin: 0;
  font-size: 15px;
  color: var(--text-secondary);
}

/* 历史记录列表 */
.rv-list {
  padding: 8px 0;
}

.rv-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color var(--transition-fast);
}

.rv-item:hover {
  background-color: var(--primary-blue-bg);
}

.rv-item-icon {
  width: 40px;
  height: 40px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
  box-shadow: var(--shadow-sm);
}

.rv-item-icon i {
  font-size: 18px;
}

.rv-item-content {
  flex: 1;
  min-width: 0;
}

.rv-item-title {
  font-size: 15px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.rv-item-meta {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: var(--text-secondary);
}

.rv-item-module {
  margin-right: 12px;
  padding: 3px 8px;
  background-color: var(--grey-100);
  border-radius: 16px;
  font-weight: 500;
  font-size: 12px;
  transition: background-color var(--transition-fast);
}

.rv-item:hover .rv-item-module {
  background-color: var(--grey-200);
}

.rv-item-time {
  flex-shrink: 0;
}

.rv-item-actions {
  display: flex;
  gap: 6px;
  margin-left: 16px;
  opacity: 0;
  transition: opacity var(--transition-fast);
}

.rv-item:hover .rv-item-actions {
  opacity: 1;
}

.rv-action-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--grey-100);
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.rv-action-btn:hover {
  background-color: var(--grey-200);
  transform: scale(1.05);
}

.rv-action-btn.pin.pinned {
  color: var(--primary-blue);
  background-color: var(--primary-blue-bg);
}

/* 固定项目部分 */
.rv-pinned-section {
  padding: 20px;
  border-top: 1px solid var(--divider);
  background-color: var(--grey-50);
}

.rv-pinned-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.rv-pinned-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.rv-pinned-item {
  display: flex;
  align-items: center;
  width: calc(50% - 8px);
  padding: 12px 16px;
  background-color: var(--background-white);
  border-radius: var(--radius-md);
  cursor: pointer;
  position: relative;
  transition: all var(--transition-normal);
  box-shadow: var(--shadow-sm);
}

.rv-pinned-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.rv-pinned-icon {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
  flex-shrink: 0;
}

.rv-pinned-content {
  flex: 1;
  min-width: 0;
}

.rv-pinned-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 0 0 4px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.rv-pinned-module {
  font-size: 12px;
  color: var(--text-secondary);
  background-color: var(--grey-100);
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
}

.rv-pinned-unpin {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--grey-100);
  border: none;
  color: var(--primary-blue);
  font-size: 12px;
  cursor: pointer;
  opacity: 0;
  transition: opacity var(--transition-fast), background-color var(--transition-fast);
}

.rv-pinned-item:hover .rv-pinned-unpin {
  opacity: 1;
}

.rv-pinned-unpin:hover {
  background-color: var(--grey-200);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .rv-pinned-item {
    width: 100%;
  }
  
  .rv-item-actions {
    opacity: 1;
  }
}
</style> 